package resources;

import bean.Term;
import com.sun.jersey.api.NotFoundException;
import exception.ManchesterQueryException;
import storage.OwllinkServer;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Sarala Wimalaratne
 *         Date: 12-Aug-2011
 *         Time: 08:52:30
 */

@Path("/terms")
public class TermsResource {

    @Context
    UriInfo uriInfo;
    @Context
    Request request;


/*    @GET
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public List<Term> getTerms() {
		return OwllinkServer.getSubClasses ("PATO_0000918");
	}*/

    @Path("/subterms/{term}")
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Term> getSubTerms(@PathParam("term") String term) {
        try {
            return OwllinkServer.getSubTerms(term);
        } catch (ManchesterQueryException e) {
            e.printStackTrace();
            throw new NotFoundException(e.getDisplayMessage());
        }
    }

    @Path("/eqterms/{term}")
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Term> getEqTerms(@PathParam("term") String term) {
        try {
            return OwllinkServer.getEquivalentTerms(term);
        } catch (ManchesterQueryException e) {
            e.printStackTrace();
            throw new NotFoundException(e.getDisplayMessage());
        }
    }

    @Path("/terms/{term}")
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Term> getTerms(@PathParam("term") String term) {
        try {
            return OwllinkServer.getTerms(term);
        } catch (ManchesterQueryException e) {
            e.printStackTrace();
            throw new NotFoundException(e.getDisplayMessage());
        }
    }

    @POST
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void newContact(
            @FormParam("name") String name,
            @Context HttpServletResponse servletResponse
    ) throws IOException {
        try {
            Term term = OwllinkServer.addTerm(name);
            if(term != null){
                URI uri = uriInfo.getAbsolutePathBuilder().path(term.getId()).build();
                Response.created(uri).build();
            }
        } catch (ManchesterQueryException e) {
            e.printStackTrace();
            throw new NotFoundException(e.getDisplayMessage());
        }

        servletResponse.sendRedirect("../pages/new_term.html");
    }
}
